import React,{Component} from "react";
import { Select, Button, Form, Input, Checkbox, Row, message} from "antd";
import { withRouter} from "react-router-dom";
import '../../editor/ueditor.config.js';
import '../../editor/ueditor.all.js';
import '../../editor/lang/zh-cn/zh-cn.js';
import config from  '../../editor/my.config';
import ajax from '../../ajaxMethod.js';

const container = "container";
class NewsDetail extends Component{
    constructor(props){
        super(props);
        this.state = {
            data:this.props.location.values?this.props.location.values.data:{
                cover:'',
                title:'',
                author:'',
                type:0,
                top:false,
                content:'',
            },
            id:this.props.location.values?(()=>{
                localStorage.setItem("id", JSON.stringify(this.props.location.values.id));
                return this.props.location.values.id;
            })():JSON.parse(localStorage.getItem("id")),
            ue: undefined,
        }
    }
    componentDidMount() {
        this.initEditor();
        this.getData();
    }
    componentWillUnmount(){
        UE.delEditor(container);
    }
    getData = ()=>{
        let _this = this;
        if(this.state.id){
            ajax.getAjax("/interface/management/news/detail",{"id": this.state.id}, res=>{
                if(res.success){
                    _this.setState({data: res.data});
                    _this.setFormValues(res.data);
                }
            },
            error=>{
                console.error(error);
            });
        }
    }
    //设置当前页面所有内容
    setFormValues = (data) =>{
        //设置图片
        let img = document.getElementById("preview");
        let ue = this.state.ue;

        //图片路径设置为读取的图片
        if(data){
            if(img){
                if(data.cover){
                    img.src = data.cover;
                    img.style.display = "block";
                    img.style.opacity = "1";
                }
            }
            //设置表单的
            this.props.form.setFieldsValue({
                title: data.title,
                author: data.author,
                type: data.type,
                top: data.top,
            });
            //设置ueditor
            if(ue){
                ue.ready(function() {
                    ue.setContent(data.content);
                })
            }
        }
    }
    initEditor = () =>{
        //加载前先卸载。和绑定事件类似
        UE.delEditor(container);
        const ueEditor = UE.getEditor(container, config);
        const self = this;
        ueEditor.ready((ueditor) => {
            if (!ueditor) {
                self.initEditor();
            }
        })
        this.setState({ue: ueEditor});
    }
    backClick = (e) =>{ this.props.history.goBack(); }
    imgPreview = (e) =>{
        //判断是否支持FileReader
        let reader;
        if (window.FileReader) {
            reader = new FileReader();
        } else {
            alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
            return;
        }
        //获取文件
        let fileDom = document.getElementById("cover");
        let file = fileDom.files[0];
        let imageType = /^image\//;
        //是否是图片
        if(file){
            if (!imageType.test(file.type)) {
                alert("请选择图片！");
                return;
            }
        }
        //读取完成
        reader.onload = function(e) {
            //获取图片dom
            let img = document.getElementById("preview");
            //图片路径设置为读取的图片
            if(img){
                img.src = e.target.result;
                img.style.display = "block";
                img.style.opacity = "1";
            }
        };
        //读取指定的 Blob 或 File 对象。读取操作完成的时候，readyState 会变成已完成DONE，并触发 loadend 事件，
        //同时 result 属性将包含一个data:URL格式的字符串（base64编码）以表示所读取文件的内容。
        reader.readAsDataURL(file);
    }
    
    //提交数据
    onSubmit = (e) =>{
        let values = this.props.form.getFieldsValue();
        let imgFile = document.getElementById("cover").files[0];
        let img = document.getElementById("preview");
        let fd = new FormData();
        let _this = this;

        values.content = this.state.ue.getContent();
        //如果没有上传新的封面就不提交封面的数据
        if(imgFile){
            fd.append("cover", imgFile, imgFile.name || ('blob.' + imgFile.type.substr('image/'.length)));
        }else{
            fd.append("cover", undefined);
        }
        //其他的内容全部提交。
        fd.append("id", this.state.id);
        fd.append("values", JSON.stringify(values));
        //按理来说这个src一定存在。
        if(img.getAttribute("src")){
            for(let item in values){
                if(!item){
                    message.error("请输入所有内容");
                    return;
                }
            }
            ajax.postBinaryAjax("/interface/management/news/changeArticle",fd,function(res){
                if(res.success){
                    message.success("提交成功");
                    //然后返回到新闻页面
                    _this.props.history.goBack();
                }else{
                    message.error("后台出错,暂时无法上传");
                }
            });
        }else{
            message.error("请上传图片封面");
        }
        e.preventDefault();
    }

    render(){
        const state = this.state;
        const _this = this;
        const { getFieldProps } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        
        return (
        <div className="news detail">
            <div className="contral">
                <Button className="back" onClick={this.backClick}>返回</Button>
            </div>
            <Form onSubmit={this.onSubmit}>
                <Form.Item label="封面" {...formItemLayout} >
                    <div className="img-box">
                        <div className="head-show">
                            <div className="cross"></div>
                            <div className="verti"></div>
                        </div>
                        <input type="file" className="head-src"
                            {...getFieldProps('cover', { rules: [{required: true, message:"请上传封面"}], onChange: this.imgPreview})}
                        />
                        <img id="preview" ></img>
                        <span className="tip">请上传图片，2m以下，尺寸：280px*120px</span>
                    </div>
                </Form.Item>
                <Form.Item label="标题" {...formItemLayout}>
                    <Input {...getFieldProps('title', { rules: [{required: true, message:"请输入标题"}]})}></Input>
                </Form.Item>
                <Form.Item label="作者" {...formItemLayout}>
                    <Input  {...getFieldProps('author', { rules: [{required: true, message:"请输入作者"}]})}></Input>
                </Form.Item>
                <Form.Item label="分类" {...formItemLayout} >
                    <Select {...getFieldProps('type',{rules:[{required: true}],initialValue: 0 })}>
                        <Select.Option value={0}>公告</Select.Option>
                        <Select.Option value={1}>机场</Select.Option>
                        <Select.Option value={2}>飞机</Select.Option>
                        <Select.Option value={3}>乘客 </Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item {...{
                    labelCol: {
                        xs: { span: 24 },
                        sm: { span: 12 },
                        //sm是表示从横坐标的8开始，24表示总共有24个
                    },
                    wrapperCol: {
                        xs: { span: 24 },
                        sm: { span: 18 },
                        //sm表示宽度
                    },
                }}>
                    <Checkbox {...getFieldProps('top')}>置顶</Checkbox>
                </Form.Item>
                <Form.Item>
                    <p className="content-tip">*插入的视频只支持mkv、avi、rmvb、.wmv、mp4格式，大小不超过30m，图片不能超过2m</p>
                    <script id={container} name="content" type="text/plain"></script>
                </Form.Item>
                <Row>
                    <Button className="submit-btn" type="primary" htmlType="submit">发布</Button>
                </Row>
            </Form>
        </div>)
    }
}

export default withRouter(Form.create({})(NewsDetail));